/**
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 * @data:2017年10月16日
 * @author:MaShibo
 */
package com.wttech.dzzf.process.service.user;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.wtkj.vo.dzzf.base.kfwd.FundAccount;
import com.wttech.dzzf.process.dao.DifferentPhoneInfosDao;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.model.CertKey;
import com.wttech.dzzf.process.model.user.DifferentPhone;

/**
 * 收集并记录： 证件号相同但手机号不同的记录
 * 
 * @date 2017年10月16日
 * @author MaShibo
 */
@Service
public class CollectDifferentPhoneInfos {
    
    
    private static final Logger LOGGER = LoggerFactory.getLogger(CollectDifferentPhoneInfos.class);
    
    private static final int DEFAULT_PROCESS_NUM = 10000;
    
    @Resource
    private DifferentPhoneInfosDao differentPhoneInfosDao;
    
    @Resource
    private TransferUserInfoDao transferUserInfoDao;
    
    @Resource
    private ThreadPoolTaskExecutor executor;
    
    public void process() {
        Integer total = differentPhoneInfosDao.queryRepeatCertInfoNum();
        LOGGER.info("共{}个待处理的证件信息", total);
        int count = (int) Math.ceil((double) total / DEFAULT_PROCESS_NUM);
        List<Future<Void>> futures = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            futures.add(executor.submit(new SubProcessThread(i + 1)));
        }
        for (Future<Void> future : futures) {
            try {
                future.get();
            } catch (InterruptedException e) {
                LOGGER.error(e.getMessage(), e);
                Thread.currentThread().interrupt();
            } catch (ExecutionException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
        executor.shutdown();
    }
    
    public class SubProcessThread implements Callable<Void> {
        
        
        private int count;
        
        /**
         * @param count
         */
        public SubProcessThread(int count) {
            super();
            this.count = count;
        }
        
        @Override
        public Void call() throws Exception {
            LOGGER.info("第{}次开始执行", count);
            int startRow = (count - 1) * DEFAULT_PROCESS_NUM + 1;
            int endRow = count * DEFAULT_PROCESS_NUM;
            List<CertKey> certKeys = differentPhoneInfosDao.queryAllRepeatCertInfos(startRow, endRow);
            for (CertKey certKey : certKeys) {
                processSingleData(certKey);
            }
            LOGGER.info("第{}次结束执行", count);
            return null;
        }
        
        private void processSingleData(CertKey certKey) {
            List<FundAccount> fundAccounts = differentPhoneInfosDao.queryFundAccountInfosByCert(certKey.getCertifiNo(),
                    certKey.getCertifiType());
            if (CollectionUtils.isEmpty(fundAccounts)) {
                return;
            }
            FundAccount first = fundAccounts.get(0);
            String agentIdNum = first.getAgentIdNum();
            String phoneNo = first.getPhone();
            for (int i = 1; i < fundAccounts.size(); i++) {
                FundAccount entry = fundAccounts.get(i);
                String tempAgentIdNum = entry.getAgentIdNum();
                String tempPhone = entry.getPhone();
                if (StringUtils.isBlank(agentIdNum) && StringUtils.isNotBlank(tempAgentIdNum)) {
                    agentIdNum = tempAgentIdNum;
                } else if (StringUtils.isBlank(agentIdNum)) {
                    continue;
                } else if (StringUtils.isNotBlank(agentIdNum) && StringUtils.isNotBlank(tempAgentIdNum)
                        && !StringUtils.equals(agentIdNum, tempAgentIdNum)) {
                    createDifferentPhoneInfos(fundAccounts);
                    break;
                }
                
                if (StringUtils.isBlank(phoneNo) && StringUtils.isNotBlank(tempPhone)) {
                    phoneNo = tempPhone;
                } else if (StringUtils.isBlank(phoneNo)) {
                    continue;
                } else if (StringUtils.isNotBlank(agentIdNum) && StringUtils.isNotBlank(tempPhone)
                        && !StringUtils.equals(phoneNo, tempPhone)) {
                    createDifferentPhoneInfos(fundAccounts);
                    break;
                }
            }
        }
        
        private void createDifferentPhoneInfos(List<FundAccount> fundAccounts) {
            for (FundAccount fundAccount : fundAccounts) {
                DifferentPhone dp = new DifferentPhone();
                dp.setOwnerType(fundAccount.getOwnerType());
                dp.setName(fundAccount.getFundAccountName());
                dp.setCertifiType(fundAccount.getCertifiType());
                dp.setCertifiNo(fundAccount.getCompanyLic());
                dp.setTopClass(fundAccount.getTopClass());
                dp.setPhoneNo(fundAccount.getPhone());
                dp.setOptOn(fundAccount.getClientOprDt());
                dp.setAgentIdNum(fundAccount.getAgentIdNum());
                dp.setAgentIdType(fundAccount.getAgentIdType());
                dp.setAgentName(fundAccount.getRelationName());
                try {
                    transferUserInfoDao.createTestObjcet(dp);
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                    LOGGER.info(dp.toString());
                }
            }
        }
        
    }
    
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        CollectDifferentPhoneInfos service = context.getBean(CollectDifferentPhoneInfos.class);
        service.process();
    }
}
